//
//  KINGEmoticonController.swift
//  表情键盘
//
//  Created by king on 15/8/6.
//  Copyright © 2015年 king. All rights reserved.
//

import UIKit

class KINGEmoticonController: UIViewController {
    /// 懒加载数据
    private lazy var packages = KINGEmoticonPackage.packages
    private lazy var cvLayout:KINGEmoticonLayout = KINGEmoticonLayout()
    /// 声明一个回调函数的变量
    private var selectEmoticonCallBack:(emoticon:KINGEmoticon)->()
    /// 重写构造函数，对callBack进行赋值
    init(select:(emoticon:KINGEmoticon)->()) {
        selectEmoticonCallBack = select
        super.init(nibName: nil, bundle: nil)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
        collectionView.registerClass(KINGEmoticonCell.self, forCellWithReuseIdentifier: "cell")
        //KINGEmoticonPackage.packages
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()

    }
    //toolbar点击事件
    func clickItem(btn:UIBarButtonItem) {
        print(btn.tag)
        let indexPath = NSIndexPath(forItem: 0, inSection: btn.tag)
        collectionView.scrollToItemAtIndexPath(indexPath, atScrollPosition: UICollectionViewScrollPosition.Left, animated: true)
    }
    //设置UI
    private func setupUI() {
        view.addSubview(toolBar)
        view.addSubview(collectionView)
        collectionView.dataSource = self
        collectionView.delegate = self
        
        toolBar.translatesAutoresizingMaskIntoConstraints = false
        collectionView.translatesAutoresizingMaskIntoConstraints = false
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[tb]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["tb":toolBar]))
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[vc]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["vc":collectionView]))
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[vc]-0-[tb(44)]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["tb": toolBar, "vc": collectionView]))
        prepareToolBar()
    }
    //准备toolBar
    private func prepareToolBar() {
        toolBar.tintColor = UIColor.darkGrayColor()
        let itemNames = packages
        var items:[UIBarButtonItem] = [UIBarButtonItem]()
        var index = 0
        for p in itemNames {
            items.append(UIBarButtonItem(title: p.groupName, style: UIBarButtonItemStyle.Plain, target: self, action: "clickItem:"))
            items.last?.tag = index++
            items.append(UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil))
        }
        items.removeLast()
        toolBar.items = items
    }
    //懒加载控件
    private lazy var toolBar:UIToolbar = {
        let tool = UIToolbar()
        return tool
    }()
    private lazy var collectionView:UICollectionView = {
        let cv = UICollectionView(frame: CGRectZero, collectionViewLayout: self.cvLayout)
        cv.backgroundColor = UIColor.whiteColor()
        return cv
    }()
    //在类中定义私有类
    class KINGEmoticonLayout: UICollectionViewFlowLayout {
        override func prepareLayout() {
            let w:CGFloat = (collectionView?.bounds.width)! / 7
            let y:CGFloat = ((collectionView?.bounds.height)! - 3 * w) * 0.5
            itemSize = CGSizeMake(w, w)
            minimumInteritemSpacing = 0
            minimumLineSpacing = 0
            scrollDirection = UICollectionViewScrollDirection.Horizontal
            
            sectionInset = UIEdgeInsetsMake(y, 0, y, 0)
            collectionView?.pagingEnabled = true
            collectionView?.showsHorizontalScrollIndicator = false
        }
    }
}

//MARK: - 遵守collection数据源协议
extension KINGEmoticonController : UICollectionViewDataSource , UICollectionViewDelegate{
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        //获取表情
        let emoticon = packages[indexPath.section].emoticons![indexPath.item]
        //添加到常用表情中
        //如果电机的是第0组，不进行排序,用户体验更好
        if indexPath.section != 0 {
            //如果是删除按钮，不进行排序
            if !emoticon.removeEmoticon {
                KINGEmoticonPackage.addFavouriteEmoticon(emoticon)
            }
        }
        //调用回调函数，将表情传递出去
        selectEmoticonCallBack(emoticon: emoticon)
    }
    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        return packages.count
    }
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        let emoticons = packages[section]
        return emoticons.emoticons!.count
    }
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier("cell", forIndexPath: indexPath) as! KINGEmoticonCell
        cell.emoticon = packages[indexPath.section].emoticons![indexPath.item]
        
        return cell
    }
}

//自定义cell
class KINGEmoticonCell:UICollectionViewCell {
    var emoticon:KINGEmoticon? {
        didSet{
            //可以直接设置值，解决图像复用问题,如果使用UIImage named的话 如果名字为“”，就会在控制台打信息
            emoticonBtn.setImage(UIImage(contentsOfFile: emoticon!.imagePath), forState: UIControlState.Normal)
            //设置emoji
            emoticonBtn.setTitle(emoticon!.emoji, forState: UIControlState.Normal)
            if emoticon?.removeEmoticon == true {
                emoticonBtn.setImage(UIImage(named: "compose_emotion_delete"), forState: UIControlState.Normal)
                //emoticonBtn.setImage(UIImage(named: "compose_emotion_delete_highlighted"), forState: UIControlState.Highlighted)
            }
        }
    }
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI() {
        contentView.backgroundColor = UIColor.orangeColor()
        contentView.addSubview(emoticonBtn)
        emoticonBtn.backgroundColor = UIColor.whiteColor()
//        emoticonBtn.frame = CGRectOffset(bounds, 4, 4)
        emoticonBtn.frame = bounds
        //禁用按钮，否则消息不能传递到控制器
        emoticonBtn.userInteractionEnabled = false
        //设置字体，可以调整图片的大小，让代理接收交互
        emoticonBtn.titleLabel?.font = UIFont.systemFontOfSize(32)
    }
    //懒加载控件
    private lazy var emoticonBtn:UIButton = UIButton()
}